package com.example.om_export.app.report.service;

import com.example.om_export.app.equipment.dao.CustomerMapper;
import com.example.om_export.app.report.dao.DocumentTemplateFieldMapper;
import com.example.om_export.app.report.dao.ReportTemplateMapper;
import com.example.om_export.app.report.entity.DocumentTemplateField;
import com.example.om_export.app.report.entity.ReportTemplate;
import com.example.om_export.common.utils.LayuiDataGrid;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CustomerService {
    @Autowired
    CustomerMapper cm;
    @Autowired
    DocumentTemplateFieldMapper dtfm;
    @Autowired
    ReportTemplateMapper rtm;
    @Autowired
    ReportService rs;

    public LayuiDataGrid getPageList(Integer page, Integer limit ,String cCusCode ,String cCusName ,String comCode ,String HospitalType ,String CustTYPE){
        Page<Object> pageInfo = PageHelper.startPage(page, limit);
        cm.findSerach(cCusCode,cCusName,comCode,HospitalType,CustTYPE);
        return LayuiDataGrid.generate(pageInfo.getTotal(), pageInfo.getResult());
    }

    public XSSFWorkbook excalDownLoad(String templateId, String cCusCode , String cCusName , String comCode , String HospitalType , String CustTYPE) {
        Map<String, Object> map = null;
        List<Map<String, Object>> dataSet = new ArrayList<Map<String, Object>>();

        //Excel表头
        StringBuffer headers = new StringBuffer();
        headers.append("[{\"field\":\"XH\",\"filedName\":\"序号\"}");
        ReportTemplate rt = rtm.selectByPrimaryKey(templateId);
        List<DocumentTemplateField> fieldList = rs.getTemplateFieldsByTemplateId(rt);

        for(DocumentTemplateField field : fieldList){
            headers.append(",{\"field\":\"" + field.getFieldName() + "\",\"filedName\":\"" + field.getFieldNameCn() + "\"}");
        }
        headers.append("]");


        List<Map<String,Object>> datas = cm.findSerachAndDown(cCusCode ,cCusName ,comCode ,HospitalType ,CustTYPE);
        String val = "";
        int i=1;
        for(Map<String,Object> data : datas){
            //追加每行数据至集合中
            map = new HashMap<String,Object>();
            map.put("XH", i);
            for(DocumentTemplateField field : fieldList){
                val = data.get(field.getFieldName())+"";
                if("null".equals(val)){val="";}
                map.put(field.getFieldName(), val);
            }
            dataSet.add(map);//追加数据
            i++;
        }
        return ExcelUtil.exportExcel(rt.getTemplateName() , headers.toString(), dataSet ,"yyyy-MM-dd");
    }

}
